package com.singerw.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;


/**
 * @version V1.0
 * @Package com.singerw.utils
 * @auhter 张欣
 * @date 2020/12/29-5:24 PM
 */

public class JwtUtils {

    /**
     * 过期时间为一天
     * TODO 正式上线更换为15分钟
     */
    private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;

    /**
     * token私钥
     */
    private static final String TOKEN_SECRET = "65D4636BF4CBC37B";

    public static final String TOKEN_PREFIX = "Bearer ";
    public static final String TOKEN_HEADER = "Authorization";

    /**
     * 生成签名,15分钟后过期
     */
    public static String createToken(String userId, String username, String role) throws UnsupportedEncodingException {
        //过期时间
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        //私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        //设置头信息
        HashMap<String, Object> header = new HashMap<>(2);
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        return JWT.create().withHeader(header)
                .withClaim("userId", userId)
                .withClaim("username", URLEncoder.encode(username,"utf-8"))
                .withClaim("role", role)
                .withExpiresAt(date).sign(algorithm);
    }

    /**
     * 鉴定token是否有效
     *
     * @param token
     * @return
     */
    public static boolean verity(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (IllegalArgumentException | JWTVerificationException e) {
            return false;
        }

    }

    public static JSONObject getPayload(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            String payload = jwt.getPayload();
            System.out.println(payload);
            return (JSONObject) JSON.parse(Base64.getDecoder().decode(payload));

        } catch (IllegalArgumentException | JWTVerificationException e) {
            return null;
        }


    }

    public static String getUserId(String token) {
        return getPayload(token).getString("userId");
    }


    public static String getUsername(String token) {
        try {
            return URLDecoder.decode(getPayload(token).getString("username"),"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "null";
    }

    public static String getUserRole(String token) {
        return getPayload(token).getString("role");
    }


    public static void main(String[] args) throws UnsupportedEncodingException {

        String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiUk9MRV9VU0VSIiwiZXhwIjoxNjExOTI1MjUzLCJ1c2VySWQiOiJhM2Q2NGEyZWIxMGRlMDY3NTYwOGZmNmY5ZjUxZmZjZSIsInVzZXJuYW1lIjoiJUU1JUJFJTkwJUU3JTk5JUJFJUU0JUJEJTk5In0.FV5yxS3XjA3CBclXNzs8ovUaiAp-NgmqHFtIxjJIUMc";
//        String token = createToken("1","啊啊啊","2");
        System.out.println(getUsername(token));
    }
}
